package com.fpt.quanlyhethongsan.controller;

import java.io.File;
import java.util.Calendar;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.struts2.ServletActionContext;

import com.fpt.quanlyhethongsan.utils.Constants;
import com.opensymphony.xwork2.ActionSupport;

public class UploadFileController extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8990332017900749251L;
	private File fileUpload;
	private String fileUploadContentType;
	private String fileUploadFileName;

	public File getFileUpload() {
		return fileUpload;
	}

	public void setFileUpload(File fileUpload) {
		this.fileUpload = fileUpload;
	}

	public String getFileUploadContentType() {
		return fileUploadContentType;
	}

	public void setFileUploadContentType(String fileUploadContentType) {
		this.fileUploadContentType = fileUploadContentType;
	}

	public String getFileUploadFileName() {
		return fileUploadFileName;
	}

	public void setFileUploadFileName(String fileUploadFileName) {
		this.fileUploadFileName = fileUploadFileName;
	}

	public String execute() {
		try {
			String extension = FilenameUtils.getExtension(this.fileUploadFileName);
			this.fileUploadFileName = String.valueOf(Calendar.getInstance().getTime().getTime()) + "." + extension;
			String filePath = ServletActionContext.getRequest().getSession().getServletContext().getRealPath("/")
					+ "FileUpload\\";
			File fileToCreate = new File(filePath, this.fileUploadFileName);

			FileUtils.copyFile(this.fileUpload, fileToCreate);
			this.fileUploadFileName = ServletActionContext.getRequest().getContextPath() + "/FileUpload/"
					+ fileUploadFileName;
		} catch (Exception e) {
			e.printStackTrace();
			return Constants.ERROR;
		}

		return Constants.SUCCESS;
	}

	public String displayFormUpload() {
		return Constants.SUCCESS;
	}
}
